package com.example.springbootblog.common.interceptor;

import com.example.springbootblog.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 首先获取 token
        String token = request.getHeader("user_header_token");
        log.info("得到的令牌为：{}",token);
//        校验 token
        Claims claims = JwtUtil.checkToken(token);
//        验证返回信息
//        如果为空就返回 401 说明登录失败
        if (claims == null) {
            log.error("Token解析失败！");
            response.setStatus(401);
            return false;
        }

        return true;
    }
}
